package com.emm.yixun.website.controller.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

/**
 * 文件上传基础类
 * 
 * @author RUING
 * 
 */
@Controller
@RequestMapping("/common/file/")
public class UploadController {
	private static Logger log = Logger.getLogger(UploadController.class);
	/*"#{configproperties['file.serviceUrl']}"*/
	@Value("${file.serviceUrl}")
	public String serviceUrl;

	/**
	 * 上传文件(apk或者UI)
	 * 
	 * @param picture
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadFile")
	public void uploadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
			throws IOException {
		String type = request.getParameter("type");
		response.setContentType("text/html; charset=utf-8");
		JSONObject res = new JSONObject();
		try {
			JSONObject params = new JSONObject();
			params.put(type, type);
			String result = FileUploadPorxyUtil.submitPost(serviceUrl, params, file);
			JSONObject jsonObject = JSONObject.parseObject(result);
			jsonObject.put("fileName", file.getOriginalFilename());
			response.getWriter().append(jsonObject.toJSONString());
		}catch (Exception e) {
			log.error("上传失败", e);
			res.put("result", "0");
			res.put("errorCode", "0000");
			res.put("errorMsg", "上传失败");
		}
	}
	
	/**
	 * 上传文件(apk或者UI)
	 * 
	 * @param picture
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/extUploadFile")
	public void extUploadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file)
			throws IOException {
		String type = request.getParameter("type");
		response.setContentType("text/html; charset=utf-8");
		JSONObject res = new JSONObject();
		try {
			JSONObject params = new JSONObject();
			params.put(type, type);
			String result = FileUploadPorxyUtil.submitPost(serviceUrl, params, file);
			JSONObject jsonObject = JSONObject.parseObject(result);
			jsonObject.put("success", true);
			jsonObject.put("fileName", file.getOriginalFilename());
			response.getWriter().append(jsonObject.toJSONString());
		}catch (Exception e) {
			log.error("上传失败", e);
			res.put("result", "0");
			res.put("errorCode", "0000");
			res.put("errorMsg", "上传失败");
		}
	}

	/**
	 * 下载服务器文件
	 * 
	 * @param request
	 * @param response
	 * @param fileUrl
	 * @param fileName
	 */
	@RequestMapping("downloadFile")
	public void download(HttpServletRequest request, HttpServletResponse response, String fileUrl, String fileName)
			throws Exception {
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		fileUrl = fileUrl.replace("?", "/");
		URL theURL = new URL(fileUrl);
		URLConnection connection = theURL.openConnection();
		try {
			// 客户使用保存文件的对话框：
			fileName = encodeChineseDownloadFileName(request, fileName);
			fileUrl = new String(fileUrl.getBytes("utf-8"), "utf-8");
			response.setContentType("application/x-msdownload");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			// 通知客户文件的MIME类型：
			bis = new java.io.BufferedInputStream(connection.getInputStream());
			bos = new java.io.BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			@SuppressWarnings("unused")
			int i = 0;

			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				i++;
			}
			bos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				bis = null;
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				bos = null;
			}
		}

	}

	/**
	 * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性
	 * 
	 * @throws UnsupportedEncodingException
	 */
	public static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
			throws UnsupportedEncodingException {

		String filename = null;
		String agent = request.getHeader("USER-AGENT");
		if (null != agent) {
			if (-1 != agent.indexOf("Firefox")) {// Firefox
				filename = "=?UTF-8?B?"
						+ (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))
						+ "?=";
			} else if (-1 != agent.indexOf("Chrome")) {// Chrome
				filename = new String(pFileName.getBytes(), "ISO8859-1");
			} else {// IE7+
				filename = java.net.URLEncoder.encode(pFileName, "UTF-8");
				filename = StringUtils.replace(filename, "+", "%20");// 替换空格
			}
		} else {
			filename = pFileName;
		}
		return filename;
	}

}
